package com.example.freemarkdemo.freemarker;

import freemarker.template.Configuration;
import freemarker.template.Template;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;
import java.io.File;
import java.io.FileWriter;
import java.io.Writer;
import java.util.HashMap;
import java.util.Map;

/**
 * freemarker生成静态模板
 */
@Controller
public class TempletController {
    @Resource
    private Configuration config;
    @RequestMapping("/test")
    public String templet(Model model){
        String str = "你好,欢迎光临";
        Map<String,Object> map = new HashMap<>();
        map.put("name",str);
        saveTemplet(map);
        model.addAttribute("name","你好世界");
        return "test";
    }

    private void saveTemplet(Map<String, Object> map) {
        try {
            //获取模板对象
            Template template = config.getTemplate("test.ftl");
            //生成模板的路径
            String path = this.getClass().getResource("/").toURI().getPath()+"static/test.html";
            System.out.println(path);
            Writer writer = new FileWriter(new File(path.substring(path.indexOf("/"))));
            template.process(map,writer);
            writer.flush();
            writer.close();
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
